package com.mygame.im.logic;

//import org.apache.kafka.clients.consumer.ConsumerRecord;
//import org.apache.kafka.clients.producer.ProducerRecord;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.kafka.annotation.KafkaListener;
//import org.springframework.kafka.core.KafkaTemplate;
//import com.mygame.gateway.message.consume.kafka.GatewayMessageConsumerService;
//import com.mygame.gateway.message.consume.kafka.GatewayMessageContext;
import com.mygame.message.dispatcher.GameMessageHandler;

@GameMessageHandler
public class IMLogicHandler {
//    @Autowired
//    private KafkaTemplate<String, byte[]> kafkaTemplate;
//    private final static String IM_TOPIC = "game-im-topic";
//    @Autowired
//    private GatewayMessageConsumerService gatewayMessageConsumerService;
//    //发布消息Kafka服务之中
//    private void publishMessage(ChatMessage chatMessage) {
//        String json = JSON.toJSONString(chatMessage);
//        try {
//            byte[] message = json.getBytes("utf8");
//            ProducerRecord<String, byte[]> record = new ProducerRecord<String, byte[]>(IM_TOPIC, "IM", message);
//            kafkaTemplate.send(record);
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//    }
//    //这里需要注意的是groupId一定要不一样，因为kafka的机制是一个消息只能被同一个消费者组下的某个消费者消费一次。不同的服务实例的serverId不一样
//    @KafkaListener(topics = {IM_TOPIC},groupId= "IM-SERVER-" + "${game.server.config.server-id}")
//    public void messageListener(ConsumerRecord<String, byte[]> record) {
//        //监听聊天服务发布的信息，收到信息之后，将聊天信息转发到所有的客户端。
//        byte[] value = record.value();
//        try {
//            String json = new String(value,"utf8");
//            ChatMessage chatMessage = JSON.parseObject(json, ChatMessage.class);
//            IMSendIMMsgeResponse response = new IMSendIMMsgeResponse();
//            response.getBodyObj().setChat(chatMessage.getChatMessage());
//            response.getBodyObj().setSender(chatMessage.getNickName());
//            //因为这里不再GatewayMessageContext参数，所以这里使用总的GameChannel管理类，将消息广播出去
//            gatewayMessageConsumerService.getGameMessageEventDispatchService().broadcastMessage(response);
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//    }
//    @GameMessageMapping(IMSendIMMsgRequest.class)//在这里接收客户端发送的聊天消息
//    public void chatMsg(IMSendIMMsgRequest request,GatewayMessageContext<IMManager> ctx) {
//        ChatMessage chatMessage = new ChatMessage();
//        chatMessage.setChatMessage(request.getBodyObj().getChat());
//        chatMessage.setNickName(request.getBodyObj().getSender());
//        chatMessage.setPlayerId(ctx.getPlayerId());
//        this.publishMessage(chatMessage);//收到客户端的聊天消息之后，把消息封装，发布到Kafka之中。
//    }


}
